<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
      <el-form-item label="数据对象名称" prop="objectName">
        <el-input
          v-model="queryParams.objectName"
          placeholder="请输入数据对象名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="数据对象标识" prop="status">-->
<!--        <el-select v-model="queryParams.status" placeholder="请输入数据对象标识" clearable size="small">-->
<!--          <el-option-->
<!--            v-for="dict in dict.type.sys_normal_disable"-->
<!--            :key="dict.value"-->
<!--            :label="dict.label"-->
<!--            :value="dict.value"-->
<!--          />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:dept:add']"
        >新增</el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="info"-->
      <!--          plain-->
      <!--          icon="el-icon-sort"-->
      <!--          size="mini"-->
      <!--          @click="toggleExpandAll"-->
      <!--        >展开/折叠</el-button>-->
      <!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="objectList"
      row-key="id"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column key="id" prop="id" label="id" width="100"></el-table-column>
      <el-table-column key="name" prop="name" label="数据对象名称" width="150"></el-table-column>
      <el-table-column key="description" prop="description" label="数据对象描述" width="150"></el-table-column>
      <el-table-column key="sqlCode" prop="sqlCode" label="sql语句" width="300"></el-table-column>
      <el-table-column key="reviseTime" prop="reviseTime" label="修改时间" width="150"></el-table-column>
      <el-table-column key="dataPath" prop="dataPath" label="对应数据表" width="150"></el-table-column>
      <el-table-column label="操作" class-name="small-padding fixed-width">
        <template slot-scope="scope">
         <el-button
           size="mini"
           type="text"
           icon="el-icon-view"
           @click="handleViewColumns(scope.row)"
           v-hasPermi="['system:dept:edit']"
         >查看列信息</el-button>
         <el-button
           size="mini"
           type="text"
           icon="el-icon-edit"
           @click="handleUpdate(scope.row)"
           v-hasPermi="['system:dept:edit']"
         >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:dept:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body width="600px">
      <el-steps :active="active">
        <!--.sync指的就是同步动态，双向的来表示visible的值-->
        <el-step title="基础信息"></el-step>
        <!--active为0时，为选中状态-->
        <el-step title="属性配置"></el-step>
        <!--active为1时，为选中状态-->
        <!-- <el-step title="映射配置"></el-step> -->
        <!--active为2时，为选中状态-->
      </el-steps>

      <el-form v-if="active===0" ref="form" :model="dataObject" :rules="rules" label-width="120px" style="margin-top:20px; margin-right:40px;margin-bottom: 50px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="数据对象名称" prop="name" required>
              <el-input v-model="dataObject.name" placeholder="请输入数据对象名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="数据对象描述" prop="description" required>
              <el-input v-model="dataObject.description" placeholder="请输入数据对象描述" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

<!--      属性配置弹窗-->
      <el-form v-if="active===1" ref="form" :model="dataObject" :rules="rules" label-width="150px" label-position="left" height="1000px" style="margin-bottom: 50px">    
       <el-form-item label="数据来源文件" prop="file">
          <div style="text-align: left">
            <el-select v-model="selectFile" @change="fileChange" placeholder="请选择数据文件">
              <el-option v-for="item in fileList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
              >
              </el-option>
            </el-select>
          </div>
        </el-form-item>

        <el-row style="margin-bottom:20px">
          <el-col :span="9">
        <el-checkbox
          v-model="modelCheck"
          @change="handleCheckChange"
        >从数据模型导入</el-checkbox>
          </el-col>
          <el-col :span="7">
          <el-select v-if="modelCheck" v-model="selectModel" filterable @change="modelChange" placeholder="请选择数据模型">
            <el-option v-for="item in modelList"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id"
            >
            </el-option>
          </el-select>
          </el-col>
         </el-row>

<!--        <el-row>-->

            <el-table :data="dataObject.columns" border stripe style="width: 100%;">
              <el-table-column prop="alias" label="属性名称">
                <template slot-scope="scope">
                  <div v-if="!modelCheck">
                    <el-input v-show="scope.row.edit" v-model="scope.row.alias" placeholder="属性名称"></el-input>
                    <span v-show="!scope.row.edit">{{scope.row.alias}}</span>
                  </div>
                  <div v-else>
                    <el-select v-model="scope.row.alias" filterable value="" placeholder="请选择特征描述">
                      <el-option
                        v-for="item in modelFeatures"
                        :key="item"
                        :label="item"
                        :value="item"
                      />
                    </el-select>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="featureKeys" label="原始列名">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.featureKey" filterable value="" placeholder="请选择列名">
                    <el-option
                      v-for="item in fileColumnList"
                      :key="item"
                      :label="item"
                      :value="item"
                    />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button v-if="scope.row.edit" type="text" size="medium" @click="confirmAdd(scope.row)">
                    <i class="el-icon-check" aria-hidden="true"></i>
                  </el-button>
                  <div v-else>
                    <el-button type="text" size="medium" @click="editDataObjectRow(scope.row)">
                      <i class="el-icon-edit" aria-hidden="true"></i>
                    </el-button>
                    <el-button type="text" size="medium" @click="deleteDataObjectRow(scope.row,scope.$index)">
                      <i class="el-icon-delete" aria-hidden="true"></i>
                    </el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
            <el-button type="text" @click="addDataObjectRow">添加特征</el-button>
      </el-form>

      <!--      属性配置弹窗-->
      <el-form v-if="active===2" ref="form"  label-width="150px" style="margin-bottom: 50px">

        <div class="app-container">
          <el-form label-position="left" label-width="80px" :model="readerForm">
            <el-form-item label="数据源">
              <el-select v-model="readerForm.id" filterable @change="rDsChange">
                <el-option
                  v-for="item in rDsList"
                  :key="item.id"
                  :label="item.datasourceName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="数据表">
              <el-select v-model="readerForm.tableName" filterable @change="rTbChange">
                <el-option v-for="item in rTbList" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <el-table v-if="rColumnList.list.length>0" :data="rColumnList.shuxing" border stripe style="width: 100%;">
<!--          <el-table-column prop="objectName" label="属性名称" >-->
            <el-table-column label="属性名称" align="center" key="alias" prop="alias" />
<!--              <el-input v-show="scope.row.shuxing.edit" v-model="scope.row.shuxing" placeholder="属性名称"></el-input>-->
<!--              <span v-show="!scope.row.shuxing.edit">{{scope.row.shuxing}}</span>-->
<el-table-column>
  <template slot-scope="scope">
    <el-select v-model="scope.row.featureKey" filterable value="" @change="update(scope.row)">
                                  <el-option
                                    v-for="item in rColumnList.list"
                                    :key="item"
                                    :label="item"
                                    :value="item"
                                  />
                                </el-select>
  </template>
</el-table-column>

<!--                        <el-table-column label="字段名" key ="ziduan" prop="ziduan">-->
<!--                          <el-select v-model="rColumnList.shuxing.ziduan" filterable value="" @change="update()">-->
<!--&lt;!&ndash;                          <el-select v-model="readerForm.id" filterable @change="rDsChange">&ndash;&gt;-->
<!--                            <el-option-->
<!--                              v-for="item in rColumnList.list"-->
<!--                              :key="item"-->
<!--                              :label="item"-->
<!--                              :value="item"-->
<!--                            />-->
<!--                          </el-select>-->

<!--                        </el-table-column>-->
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button v-if="scope.row.edit" type="text" size="medium" @click="confirmAdd(scope.row)">
                <i class="el-icon-check" aria-hidden="true"></i>
              </el-button>
              <div v-else>
                <el-button type="text" size="medium" @click="editDataObjectRow(scope.row)">
                  <i class="el-icon-edit" aria-hidden="true"></i>
                </el-button>
                <el-button type="text" size="medium" @click="deleteDataObjectRow(scope.row,scope.$index)">
                  <i class="el-icon-delete" aria-hidden="true"></i>
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <el-row style="position: absolute; right: 20px; bottom:20px;">
        <el-button id="prveBtn" type="primary" plain @click="prve" v-if="active===1">上一步</el-button>
        <!--当active为1或2时显示按钮，点击执行prve方法-->
        <el-button id="nextBtn" type="primary" plain @click="next" v-if="active===0">下一步</el-button>
        <!--当active为1或0时显示按钮，点击执行next方法-->
        <el-button type="primary" @click="addDataObject" v-if="active===1">提交</el-button>
        <!--调用submitForm方法，关闭对话框-->
      </el-row>
    </el-dialog>

    <el-dialog title="查看数据对象列信息" :visible.sync="columnDialog.open" width="600px" append-to-body>
      <el-table :data="columnDialog.columns" border stripe style="width: 100%;">
        <el-table-column label="属性名称" key="alias" prop="alias" />
        <el-table-column label="原始列名" key="featureKey" prop="featureKey" />
        <el-table-column label="数据表" key="tableName" prop="tableName" />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="columnDialog.open=false;">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getDataObjectList,
  getDataObject,
  listDataObject,
  uploadFile,
  getTopData,
  getTables,
  getColumns,
  jdbcDsList,
  addDataObject,
  deleteDataObject,
  getParsedFile,
  getFileColumns,
  getDetail
} from '@/api/manage/dataObject'
import {getDataModels , getDataModelById} from '@/api/manage/dataModel'
// import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import item from '@/layout/components/Sidebar/Item'
import { objectMerge } from '@/utils'
// import mysqlReader from '@/views/manage/dataObject/reader/mysqlReader'

export default {
  name: "dataObject",
  // components: { mysqlReader },
  dicts: ['sys_normal_disable'],
  // components: { Treeselect },
  data() {
    return {
      jdbcDsQuery: {
        current: 1,
        size: 50
      },
      readerForm: {
        datasourceId: undefined,
        tableName: '',
        columns: [],
        where: '',
        querySql: '',
        checkAll: false,
        isIndeterminate: true,
        column:""
      },
      columnDialog: {
          open:false,
          loading: false,
          columns:[]
      },
      rDsList: [],
      rTbList: [],
      rColumnList: {
        list:[],
        shuxing:[]
      } ,
      objectList:[],
      modelList:[],
      modelFeatures:[],
      fileList:[],
      fileColumnList:[],
      // config
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 表格树数据
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      active:0,
      editForm: {},
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      selectModel:"",
      selectFile: "",
      a:"",
      // 查询参数
      queryParams: {
        coopName: undefined,
        status: undefined
      },
      dataObject:{
        name:"",
        description:"",
        sqlCode:"",
        columns:[]
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {

      },
      uploadedFile:{},
      modelCheck:false,
    };
  },

  created() {
    this.getList();
    this.getParsedFiles();
    // this.getJdbcDs();
  },
  computed:{
  },
  methods: {
    getParsedFiles() {
      getParsedFile().then(response=>{
        this.fileList = response.data
      })
    },
    // 获取可用数据源
    addDataObjectRow(){
      // const that = this;
      this.dataObject.columns.push({
        edit:true,
      });
    },
    confirmAdd(row) {
      row.edit = false;
    },
    deleteDataObjectRow(row,index){
      if(index >= 0){
        this.dataObject.columns.splice(index,1);
      }
    },
    editDataObjectRow(row){
      console.log(row);
      row.edit = true;
    },
    handleCheckChange(){
      getDataModels().then(response => {
        this.modelList = response.data;
      })
    },
    modelChange(e){
      // this.$forceUpdate();
      getDataModelById({modelId:e}).then(response => {
        console.log(response.data);
        this.modelFeatures = response.data.features.map(item => {
          return item.description
        },this);
        // console.log(this.dataObject.alias);
      })

    },
    fileChange(e) {
      getFileColumns(e).then(response => {
        console.log(response.data)
        this.fileColumnList = response.data.columns
      })
    },
    getJdbcDs() {

      this.loading = true
      jdbcDsList(this.jdbcDsQuery).then(response => {

        this.rDsList = response.data.records

        this.loading = false
      })
      // console.log(this.rDsList);
    },
    getTables(type) {
      if (type === 'reader') {
        const obj = {
          datasourceId: this.readerForm.datasourceId
        }
        //组装
        getTables(obj).then(response => {
          // console.log(response.data+"11");
          this.rTbList = response.data
        })
        // console.log(this.rTbList+"22");
      }
    },
    // reader 数据源切换
    rDsChange(e) {
      // 清空
      this.readerForm.tableName = ''
      this.readerForm.datasourceId = e
      // 获取可用表
      this.getTables('reader')
    },
    getTableColumns() {
      const obj = {
        datasourceId: this.readerForm.datasourceId,
        tableName: this.readerForm.tableName
      }
      getColumns(obj).then(response => {
        // console.log(response.data+"0");
        this.rColumnList.list = response.data;
        // this.dataObject.push({cList:this.rColumnList});
        // console.log(this.dataObject.list);
        this.rColumnList.shuxing = this.dataObject.columns;
        // console.log(this.rColumnList.shuxing);
        // this.readerForm.columns = response;
        // this.readerForm.checkAll = true;
        // this.readerForm.isIndeterminate = false;
      })
      // console.log(this.rColumnList+"1");
    },
    getColumns(type) {
      if (type === 'reader') {
        if (this.readerForm.querySql !== '') {
          this.getColumnsByQuerySql()
        } else {
          this.getTableColumns()
        }
      }
    },
    // 表切换
    rTbChange(t) {
      this.readerForm.tableName = t
      this.dataObject.columns.forEach(item => {
        item.tableName = t;
      });
      this.rColumnList.list = []
      this.readerForm.columns = []
      this.getColumns('reader')
    },
    update(row){
// console.log(row);
    },

    getData() {
      return this.readerForm
    },

    openDig() {
      this.active = 0; //重置active
      this.open = true; //设置open为true显示dialog对话框
    },
    prve() {
      --this.active;//active自减一
      if (this.active < 0) this.active = 0;//设置active最小值
      // console.log(this.$refs.myReader.rDsList);
    },
    next() {
      ++this.active;
      if (this.active > 2) this.active = 2;
    },
/**上传文件**/
    getFile(event) {
      this.file = event.target.files[0];
    },
    async upload() {
      let formData = new FormData();
      if(this.file!=undefined){
      formData.append("file", this.file);
      }
      if(!formData.has("file")){
        this.$modal.msgSuccess("请选择文件");
      }else {
      await uploadFile(formData).then(response =>{
        this.$modal.msgSuccess("上传成功");
        this.uploadedFile = response.data;
      });

        getTopData(this.uploadedFile.fileId).then(response =>{
          // console.log(response.data.default.data[0])
          this.dataObject.alias = response.data.default.data[0].map(item=>{
            return{
              columnName:item,
              edit:false
            }
            });
        })
      }
    },

    /** 查询合作机构列表 */
    getList() {
      this.loading = true;
      getDataObjectList().then(response => {
        this.objectList = response.data;
      })
      this.loading = false;
    },
    /** 转换合作机构数据结构 */
    // normalizer(node) {
    //   if (node.children && !node.children.length) {
    //     delete node.children;
    //   }
    //   return {
    //     id: node.coopId,
    //     label: node.bankName,
    //     children: node.children
    //   };
    // },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.dataObject = {
        name:"",
        description:"",
        sqlCode:"",
        columns:[]
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      // console.log(row)
      this.reset();
      this.open = true;
      // if (row.address != undefined) {
      //   this.title = "添加机构";
      //   this.form.parentId = row.coopId;
      // }else {
      this.title = "添加数据对象";
      let data=[{
        "coopId": 0,
        "parentId": 0,
        "coopName": "无",
        "children": [],
      }];
      // this.coopOptions=data;
      // this.form.parentId = 0;
      return;
      // }
      // listBank().then(response => {
      //   console.log(response.data)
      //   this.bankOptions = this.handleTree(response.data, "bankId");
      // });

    },
    handleViewColumns(row) {
      this.columnDialog.open=true;
      this.columnDialog.loading = true;
      getDetail(row.id).then(response => {
        console.log(response.data)
        this.columnDialog.columns =response.data.columns;
        this.columnDialog.loading = false;
      })
    },
    addDataObject(){
      let tableName = "";
      for (let file of this.fileList) {
        if (file.id === this.selectFile) {
          tableName = file.path
        }
      }
      this.dataObject.columns = this.dataObject.columns.map(item => {
        return {
          alias: item.alias,
          featureKey: item.featureKey,
          tableName: tableName
        }
      },this)
      this.dataObject.sqlCode = "SELECT ";
      this.dataObject.columns.forEach(item => {
        this.dataObject.sqlCode += tableName +"." +item.featureKey + " as " + item.alias +","
      });
      this.dataObject.sqlCode = this.dataObject.sqlCode.slice(0,this.dataObject.sqlCode.length-1);
      this.dataObject.sqlCode += " from " + tableName;
      console.log(this.dataObject)
      addDataObject(this.dataObject).then(response => {
          if (response.message == "操作成功") {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          }else {
            this.$modal.msgError(response.message);
          }
      });
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      // this.reset();
      // getDataObject(row.id).then(response => {
      //   this.form = response.data;
      //   this.open = true;
      //   this.title = "修改数据对象";
      // });
      // listDataObject().then(response => {
      //   this.coopOptions = response.data
      // });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.coopId != undefined) {
            updateCoop(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCoop(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除名称为"' + row.name + '"的数据项？').then(function() {
        return deleteDataObject(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    }
  }
};
</script>
